//
//  NIBaseViewController.m
//  gweAD
//
//  Created by navinfo air on 2016/10/31.
//  Copyright © 2016年 mengy. All rights reserved.
//

#import "NIBaseViewController.h"
#import "NIAlertViewController.h"
#import <MessageUI/MessageUI.h>
#import "NINavigationController.h"
#import "AppDelegate.h"
#import "MainViewController.h"
static NSDictionary *pageNameDic;

@interface NIBaseViewController ()<MFMessageComposeViewControllerDelegate>
{
}

@end

@implementation NIBaseViewController{
    
}
#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    
    self.navigationController.navigationBar.translucent = NO;
    //隐藏系统自带返回按钮
    self.navigationController.navigationBar.backIndicatorImage = [[UIImage alloc]init];
    self.navigationController.navigationBar.backIndicatorTransitionMaskImage = [[UIImage alloc]init];
    
    //去掉底部黑线
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init]
                                                 forBarPosition:UIBarPositionAny
                                                     barMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    
    [self setValueForController];

    if (_isForceLandscape) {
        // 表示本类支持旋转
        [UIViewController attemptRotationToDeviceOrientation];
    }

}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    [self recursionToModifyTextFieldTintColorWithView:self.view];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"class = %@",[self class]);
    
    if (_isForceLandscape) {
        
        [self setOrientationLandscapeRight];
    }
    else
    {
        
        [self setOrientationLandscapePortrait];
    }
    
    //以下代码为重置导航栏各种按钮
    [self setBackBtnWithImageName:@"back"];
    [self hiddenRightBtn1];
    [self hiddenRightBtn2];
    [self setRightBtn1Enable:YES];
    [self setRightBtn2Enable:YES];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    if (_isForceLandscape)
    {
        [self setOrientationLandscapePortrait];
    }
    
}
#pragma mark ------- 页面相关 -------

- (CGFloat)getScreenWidth{
    return [[UIScreen mainScreen] bounds].size.width;
}
- (CGFloat)getScreenHeight{
    return [[UIScreen mainScreen] bounds].size.height;
}

- (CGFloat)getStatusBarHeight{
    CGRect rect = [[UIApplication sharedApplication] statusBarFrame];
    return rect.size.height;
}
#pragma mark 显示无数据页面

-(void)showNoDataImage
{
    _noDataView=[[UIImageView alloc] init];
    [_noDataView setImage:[UIImage imageNamed:@"generl_nodata"]];
    
    kWeakSelf(self)
    [self.view.subviews enumerateObjectsUsingBlock:^(UITableView* obj, NSUInteger idx, BOOL *stop) {
        if ([obj isKindOfClass:[UITableView class]]) {
            [weakself.noDataView setFrame:CGRectMake(0, 0,obj.frame.size.width, obj.frame.size.height)];
            [obj addSubview:weakself.noDataView];
        }
    }];
}

#pragma mark 移除无数据页面

-(void)removeNoDataImage{
    if (_noDataView) {
        [_noDataView removeFromSuperview];
        _noDataView = nil;
    }
}
#pragma mark  动态更新状态栏颜色

- (UIStatusBarStyle)preferredStatusBarStyle{
    return _StatusBarStyle;
}
//动态更新状态栏颜色
-(void)setStatusBarStyle:(UIStatusBarStyle)StatusBarStyle{
    _StatusBarStyle=StatusBarStyle;
    [self setNeedsStatusBarAppearanceUpdate];
}

#pragma mark 递归改变TextField光标颜色

- (void)recursionToModifyTextFieldTintColorWithView:(UIView *)view
{
    if ([view.class isSubclassOfClass:[UITextField class]]) {
        [view setTintColor:[UIColor redColor]];
        
    }
    if ([view.subviews count] > 0) {
        for (UIView *subView in view.subviews) {
            [self recursionToModifyTextFieldTintColorWithView:subView];
        }
    }else{
        return;
    }
}

- (void)cancelFirstResponderWithView:(UIView *)view
{
    if (view.isFirstResponder) {
        [view resignFirstResponder];
    }
    if ([view.subviews count] > 0) {
        for (UIView *subView in view.subviews) {
            [self cancelFirstResponderWithView:subView];
        }
    }else{
        return;
    }
}
#pragma mark 设置初始值（页面传值）
-(void)setValueForController{
    
}

#pragma mark 设置双色Label

- (void)setValueAndUnitForLabel:(UILabel *)label valueForLabel:(NSString *)value unitForLabel:(NSString *)unit colorForValue:(UIColor *)vColor colorForUnit:(UIColor *)uColor fontForValue:(UIFont *)valueFont fontForUnit:(UIFont *)unitFont{
    
    [label setBackgroundColor:[UIColor clearColor]];
    NSString *text = [NSString stringWithFormat:@"%@%@",value,unit];
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:text];
    
    NSRange unitRange = [text rangeOfString:unit];
    NSRange valueRange = [text rangeOfString:value];
    
    [AttributedStr addAttribute:NSFontAttributeName
                          value:valueFont
                          range:valueRange];
    [AttributedStr addAttribute:NSForegroundColorAttributeName
                          value:vColor
                          range:valueRange];
    [AttributedStr addAttribute:NSFontAttributeName
                          value:unitFont
                          range:unitRange];
    [AttributedStr addAttribute:NSForegroundColorAttributeName
                          value:uColor
                          range:unitRange];
    
    label.attributedText = AttributedStr;
}

#pragma mark 设置为圆圈按钮

- (void)createCircleButton:(UIButton *)targetButton{
    targetButton.layer.borderWidth = 1.0f;
    targetButton.layer.masksToBounds = YES;
    targetButton.layer.borderColor = [UIColor orangeColor].CGColor;
    targetButton.layer.cornerRadius = targetButton.frame.size.width/2;
    [targetButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [targetButton setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
    [targetButton setTitleColor:[UIColor orangeColor] forState:UIControlStateDisabled];
}
#pragma mark -------- NavigationBar相关 --------
#pragma mark  导航栏点击按钮执行，若子类有需要，请复写以下相应方法
-(void)onClickBackButton
{
    [self back];
}
-(void)setTitle:(NSString *)title
{
    UINavigationController *nav = [self getNavigationController];
    if ([nav isKindOfClass:[NINavigationController class]]) {
        NINavigationController * navigation = (NINavigationController *)nav;
        [navigation.titleView setTitle:title];
    }
}

-(void)setBackBtnWithImageName:(NSString *)imageName
{
    UINavigationController *nav = [self getNavigationController];
    if ([nav isKindOfClass:[NINavigationController class]]) {
        NINavigationController * navigation = (NINavigationController *)nav;
        [navigation.titleView setBackBtnWithImageName:imageName];
    }
}

-(void)setBackBtnWithImageName:(NSString *)imageName action:(SEL)action target:(id)target
{
    UINavigationController *nav = [self getNavigationController];
    if ([nav isKindOfClass:[NINavigationController class]]) {
        NINavigationController * navigation = (NINavigationController *)nav;
        [navigation.titleView setBackBtnWithImageName:imageName action:action target:target];
    }
}

-(void)setRightBtn1WithImageName:(NSString *)imageName action:(SEL)action target:(id)target
{
    UINavigationController *nav = [self getNavigationController];
    if ([nav isKindOfClass:[NINavigationController class]]) {
        NINavigationController * navigation = (NINavigationController *)nav;
        [navigation.titleView setRightBtn1WithImageName:imageName action:action target:target];
    }
}

-(void)setRightBtn2WithImageName:(NSString *)imageName action:(SEL)action target:(id)target
{
    UINavigationController *nav = [self getNavigationController];
    if ([nav isKindOfClass:[NINavigationController class]]) {
        NINavigationController * navigation = (NINavigationController *)nav;
        [navigation.titleView setRightBtn2WithImageName:imageName action:action target:target];
    }
}
-(void)setRightBtn2WithTitle:(NSString *)title backgroundImageName:(NSString *)imageName action:(SEL)action target:(id)target
{
    UINavigationController *nav = [self getNavigationController];
    if ([nav isKindOfClass:[NINavigationController class]]) {
        NINavigationController * navigation = (NINavigationController *)nav;
        [navigation.titleView setRightBtn2WithTitle:title backgroundImageName:imageName action:action target:target];
    }
}

-(void)setRightBtn1WithTitle:(NSString *)title backgroundImageName:(NSString *)imageName action:(SEL)action target:(id)target
{
    UINavigationController *nav = [self getNavigationController];
    if ([nav isKindOfClass:[NINavigationController class]]) {
        NINavigationController * navigation = (NINavigationController *)nav;
        [navigation.titleView setRightBtn1WithTitle:title backgroundImageName:imageName action:action target:target];
    }
}


-(void)hiddenRightBtn1
{
    UINavigationController *nav = [self getNavigationController];
    if ([nav isKindOfClass:[NINavigationController class]]) {
        NINavigationController * navigation = (NINavigationController *)nav;
        [navigation.titleView hiddenRightBtn1];
    }
}

-(void)hiddenRightBtn2
{
    UINavigationController *nav = [self getNavigationController];
    if ([nav isKindOfClass:[NINavigationController class]]) {
        NINavigationController * navigation = (NINavigationController *)nav;
        [navigation.titleView hiddenRightBtn2];
    }
}

-(void)setRightBtn1Enable:(BOOL)enable
{
    UINavigationController *nav = [self getNavigationController];
    if ([nav isKindOfClass:[NINavigationController class]]) {
        NINavigationController * navigation = (NINavigationController *)nav;
        [navigation.titleView setRightBtn1Enable:enable];
    }
}

-(void)setRightBtn2Enable:(BOOL)enable
{
    UINavigationController *nav = [self getNavigationController];
    if ([nav isKindOfClass:[NINavigationController class]]) {
        NINavigationController * navigation = (NINavigationController *)nav;
        [navigation.titleView setRightBtn2Enable:enable];
    }
}

-(void)setBackBtnHidden:(BOOL)hidden
{
    UINavigationController *nav = [self getNavigationController];
    if ([nav isKindOfClass:[NINavigationController class]]) {
        NINavigationController * navigation = (NINavigationController *)nav;
        [navigation.titleView setBackBtnHidden:hidden];
    }
}

#pragma mark ------- 返回相关 -------
#pragma mark 返回上一页

- (void)back{
    NINavigationController *nav = (NINavigationController*)self.navigationController;
    if (nav) {
        [nav popViewControllerAnimated:YES];
    }
}

#pragma mark 返回到某个类

- (BOOL)backToClass:(Class)targetClass{
    NSArray *controllers = self.navigationController.childViewControllers;
    
    UIViewController *c;
    for (int i = 0; i < controllers.count; i ++) {
        c = [controllers objectAtIndex:i];
        if([c isKindOfClass:targetClass]){
            [self.navigationController popToViewController:c animated:YES];
            return YES;
            break;
        }
    }
    return NO;
}

#pragma mark 查找targetClass

- (UIViewController *)findViewControllerWithClass:(Class)targetClass{
    NSArray *controllers = self.navigationController.childViewControllers;
    UIViewController *c;
    UIViewController *viewController = nil;
    for (int i = 0; i < controllers.count; i ++) {
        c = [controllers objectAtIndex:i];
        if([c isKindOfClass:[targetClass class]]){
            viewController = c;
            break;
        }
    }
    return viewController;
}

#pragma mark 查找targetClass并pop

- (UIViewController *)findViewControllerAndBackWithClass:(Class)targetClass{
    NSArray *controllers = self.navigationController.childViewControllers;
    
    UIViewController *c;
    UIViewController *viewController = nil;
    for (int i = 0; i < controllers.count; i ++) {
        c = [controllers objectAtIndex:i];
        if([c isKindOfClass:[targetClass class]]){
            [self.navigationController popToViewController:c animated:YES];
            viewController = c;
            break;
        }
    }
    return viewController;
}

#pragma mark Dealloc后如果还有PresentController，则dismiss。

- (void)viewDidBack{
    if (IOS_VERSION < 9.0) {
        if(self.presentedViewController) {
            UIViewController* presentedViewController = self.presentedViewController;
            [presentedViewController dismissViewControllerAnimated:YES completion:^{
                
            }];
        }
    }
}

#pragma mark ------- 提示相关 -------

- (void)onCancelActionClick{
    
}

- (void)onActionClick{
    
}

- (void)onCancelActionClickWithTag:(NSInteger)tag{
    
}

- (void)onActionClickWithTag:(NSInteger)tag{
    
}


- (void)onActionSheetSelect:(NSString *)text actionTag:(NSInteger)tag{
    
}

- (void)showActionSheet:(NSArray *)array title:(NSString *)title destructiveIndex:(NSInteger)destructiveIndex actionTag:(NSInteger)tag{
    UIAlertController *c = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    UIAlertAction *action;
    for (int i = 0; i < [array count]; i++) {
        UIAlertActionStyle style;
        if (i == destructiveIndex) {
            style = UIAlertActionStyleDestructive;
        }else{
            style = UIAlertActionStyleDefault;
        }
        action = [UIAlertAction actionWithTitle:[array objectAtIndex:i] style:style handler:^(UIAlertAction * _Nonnull action) {
            [self onActionSheetSelect:[array objectAtIndex:i] actionTag:tag];
        }
                  ];
        [c addAction:action];
    }
    [c addAction:cancelAction];
    
    [self presentViewController:c animated:YES completion:nil];
    
}
- (void)showActionSheet:(NSArray *)array title:(NSString *)title actionTag:(NSInteger)tag{
    [self showActionSheet:array title:title destructiveIndex:-1 actionTag:tag];
    
}

- (void)showDateActionSheet:(UIDatePickerMode)mode{
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    datePicker.datePickerMode = mode;
    
    UIAlertController *c = [UIAlertController alertControllerWithTitle:nil message:@"请选择" preferredStyle:UIAlertControllerStyleActionSheet];
    [c.view addSubview:datePicker];
    UIAlertAction *finishAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [c addAction:finishAction];
    
    [self presentViewController:c animated:YES completion:nil];
}

- (void)showAlert:(NSString *)title{
    NIAlertViewController *c = [NIAlertViewController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    [c setImageAndTitleFont:nil titleFont:[UIFont systemFontOfSize:17] messageFont:nil];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self onCancelActionClick];
    }];
    [c addAction:cancelAction];
    [self presentViewController:c animated:YES completion:^{
        
    }];
}

- (void)showToast:(NSString *)text{
    if (text) {
        [NIToast showInfo:text];
    }
}

- (void)showAlertWithActionTitle:(NSString *)title ActionTitle:(NSString *)aTitle{
    NIAlertViewController *c = [NIAlertViewController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    [c setImageAndTitleFont:nil titleFont:[UIFont systemFontOfSize:17] messageFont:nil];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self onCancelActionClick];
    }];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:aTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self onActionClick];
    }];
    [c addAction:cancelAction];
    [c addAction:otherAction];
    [self presentViewController:c animated:YES completion:^{
        
    }];
}

- (void)showAlertWithActionTitle:(NSString *)title ActionTitle:(NSString *)aTitle cancelActionTitle:(NSString *)cancelTitle{
    NIAlertViewController *c = [NIAlertViewController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    [c setImageAndTitleFont:nil titleFont:[UIFont systemFontOfSize:17] messageFont:nil];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self onCancelActionClick];
    }];
    [c addAction:cancelAction];
    if (aTitle) {
        UIAlertAction *otherAction = [UIAlertAction actionWithTitle:aTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self onActionClick];
        }];
        [c addAction:otherAction];
    }
    
    [self presentViewController:c animated:YES completion:^{
        
    }];
}

- (void)showAlertWithActionTitle:(NSString *)title ActionTitle:(NSString *)aTitle cancelActionTitle:(NSString *)cancelTitle tag:(NSInteger)tag{
    if (!title) {
        title = @"";
    }
    NIAlertViewController *c = [NIAlertViewController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    [c setImageAndTitleFont:nil titleFont:[UIFont systemFontOfSize:17] messageFont:nil];
    if (cancelTitle) {
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self onCancelActionClickWithTag:tag];
        }];
        
        [c addAction:cancelAction];
    }
    if (aTitle) {
        UIAlertAction *otherAction = [UIAlertAction actionWithTitle:aTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self onActionClickWithTag:tag];
        }];
        [c addAction:otherAction];
    }
    
    [self presentViewController:c animated:YES completion:^{
        
    }];
}







- (void)pushFromDown:(UIStoryboardSegue *)segue{
    //定制动画
    UIViewController* source = segue.sourceViewController;
    UIGraphicsBeginImageContext(source.view.bounds.size);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    [source.view.layer renderInContext:contextRef];
    UIImage* sourceImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView* iView0 = [[UIImageView alloc] initWithImage:sourceImage];
    [iView0 setBackgroundColor:[UIColor grayColor]];
    iView0.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    iView0.frame = CGRectMake(0, 0, source.parentViewController.view.frame.size.width, source.parentViewController.view.frame.size.height);
    
    [source.parentViewController.view insertSubview:iView0 aboveSubview:source.view];
    
    
    UIViewController* destination = segue.destinationViewController;
    UIGraphicsBeginImageContext(destination.view.bounds.size);
    contextRef = UIGraphicsGetCurrentContext();
    [destination.view.layer renderInContext:contextRef];
    UIImage* desImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView* iView = [[UIImageView alloc] initWithImage:desImage];
    [iView setBackgroundColor:[UIColor grayColor]];
    iView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    iView.frame = CGRectMake(0, source.parentViewController.view.frame.size.height, source.parentViewController.view.frame.size.width, source.parentViewController.view.frame.size.height);
    
    [source.parentViewController.view insertSubview:iView aboveSubview:source.view];
    
    
    [UIView animateWithDuration:0.5f animations:^{
        iView.frame = CGRectMake(0, 20.0f,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height);
        [[[UIApplication sharedApplication] keyWindow] layoutIfNeeded];
    } completion:^(BOOL finished) {
        [iView removeFromSuperview];
        [iView0 removeFromSuperview];
    }];
}

- (void)backToClassFromTop:(Class)targetClass{
    //自定义下滑动画
    UIViewController *rootViewController = [self.navigationController.childViewControllers objectAtIndex:0];
    
    UIGraphicsBeginImageContext(rootViewController.view.bounds.size);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    [rootViewController.view.layer renderInContext:contextRef];
    UIImage* desImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView* iView = [[UIImageView alloc] initWithImage:desImage];
    [iView setBackgroundColor:[UIColor grayColor]];
    iView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    
    iView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    
    [self.view.superview insertSubview:iView belowSubview:self.view];
    
    [UIView animateWithDuration:0.5f animations:^{
        self.view.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height);
        [[[UIApplication sharedApplication] keyWindow] layoutIfNeeded];
    } completion:^(BOOL finished) {
        NSArray *controllers = self.navigationController.childViewControllers;
        BOOL found = NO;
        UIViewController *c;
        for (int i = 0; i < controllers.count; i ++) {
            c = [controllers objectAtIndex:i];
            if([c isKindOfClass:targetClass]){
                found = YES;
                [self.navigationController popToViewController:c animated:NO];
                break;
            }
        }
        if (!found) {
            [self.navigationController popToRootViewControllerAnimated:NO];
        }
        
        [iView removeFromSuperview];
    }];
}


- (void)backFromTop{
    //自定义下滑动画
    UIViewController *rootViewController = [self.navigationController.childViewControllers objectAtIndex:0];
    
    UIGraphicsBeginImageContext(rootViewController.view.bounds.size);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    [rootViewController.view.layer renderInContext:contextRef];
    UIImage* desImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView* iView = [[UIImageView alloc] initWithImage:desImage];
    [iView setBackgroundColor:[UIColor grayColor]];
    iView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    
    iView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    
    [self.view.superview insertSubview:iView belowSubview:self.view];
    
    [UIView animateWithDuration:0.5f animations:^{
        self.view.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height);
        [[[UIApplication sharedApplication] keyWindow] layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self.navigationController popToRootViewControllerAnimated:NO];
        [iView removeFromSuperview];
    }];
}



//- (void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:animated];
//    if (!pageNameDic) {
//        pageNameDic = @{@"LoginViewController":@"登录页面",@"InputPhoneNumberViewController":@"注册输入手机号页面",@"SetPasswordViewController":@"设置密码页面",@"ControlHistoryViewController":@"控制历史页面",@"VehicleDataViewController":@"首页页面",@"NewsViewController":@"消息列表页",@"RemoteControlViewController":@"控制页面",@"ControlHistoryViewController":@"远程控制历史",@"ClimateViewController":@"空调页面",@"ClimateSettingViewController":@"空调设置页面",@"ServiceViewController":@"服务页面",@"MapViewController":@"地图页面",@"ElecFenceViewController":@"电子围栏列表页",@"ElecFenceAlarmListViewController":@"围栏报警记录",@"VehicleInfoViewController":@"车辆信息页面",@"SecurityPasswordViewController":@"安全密码管理页面",@"AccountViewController":@"当前帐号页面",@"ChangePasswordViewController":@"修改登录密码页面",@"AboutViewController":@"关于页面",@"IntroductionViewController":@"功能介绍页面",@"FaqViewController":@"常见问题页面",@"ReservationViewController":@"维修保养页面",@"ReservationHistoryViewController":@"维修保养页面",@"MaintainViewController":@"保养指南页面",@"DashboardViewController":@"仪表盘列表页面",@"InstructionsViewController":@"车型说明页面",@"FaultDetectionViewController":@"深度检测页面",@"PartsSearchViewController":@"配件查询页面",@"ServiceEvaluateViewController":@"评价页面",@"ServiceEvaluateDoneViewController":@"评价完成页",@"EmergencyContactViewController":@"紧急联系人页面",@"TServiceViewController":@"基础服务状态页",@"EServiceViewController":@"尊享服务状态页",@"ServiceStationDetailViewController":@"服务站详情页",@"DetectionReportViewController":@"检测报告页",@"MaintainRecordDetailViewController":@"维保详情页",@"ChargingViewController":@"充电页",@"ChargingSettingViewController":@"充电设置页"};
//
//
//    }
//
//    //和用户中心 意见反馈
//    NSString *pageName = [pageNameDic objectForKey:[NSString stringWithFormat:@"%@",[self class]]];
//    if(pageName){
//        if (DEMO_WORKING) {
//            pageName = [NSString stringWithFormat:@"%@(游客)",pageName];
//        }
//        [MobClick beginLogPageView:pageName];
//    }
//}


//- (void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
//
//    NSString *pageName = [pageNameDic objectForKey:[NSString stringWithFormat:@"%@",[self class]]];
//    if (pageName) {
//        if (DEMO_WORKING) {
//            pageName = [NSString stringWithFormat:@"%@(游客)",pageName];
//        }
//        [MobClick endLogPageView:pageName];
//    }
//}

//- (void)uMengClick:(NSString *)eventID{
//#ifdef UMENG_ANALYTICS
//    if (DEMO_WORKING) {
//        [MobClick event:[NSString stringWithFormat:@"demo_%@",eventID]];
//    }else{
//        [MobClick event:eventID];
//    }
//#endif
//}



-(void)showMessageView : (NSString *)phone title : (NSString *)title body : (NSString *)body
{
    if( [MFMessageComposeViewController canSendText] )
    {
        MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init];
        controller.recipients = [NSArray arrayWithObject:phone];
        controller.body = body;
        controller.messageComposeDelegate = self;
        [self presentViewController:controller animated:YES completion:nil];
        
        [[[[controller viewControllers] lastObject] navigationItem] setTitle:title];//修改短信界面标题
    }
    else
    {
        [self showAlertWithActionTitle:@"该设备不支持短信功能" ActionTitle:@"提示信息"];
    }
}

-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    switch (result) {
        case MessageComposeResultCancelled:
        {
            //click cancel button
        }
            break;
        case MessageComposeResultFailed:// send failed
            
            break;
            
        case MessageComposeResultSent:
        {
            //do something
        }
            break;
        default:
            break;
    }
    
}


//关闭某个controller的alertview.
- (void)closeAlertController:(void (^ )(BOOL))completion{
    UIViewController *controller = [[self.navigationController childViewControllers] lastObject];
    if ([controller.presentedViewController isKindOfClass:[NIAlertViewController class]]) {
        if([[(NIAlertViewController *)controller.presentedViewController tag] isEqualToString:@"conflictUser"]){
            completion(NO);
            return;
        }
    }
    if (controller.presentedViewController) {
        [controller.presentedViewController dismissViewControllerAnimated:NO completion:^{
            completion(YES);
            return;
        }];
    }else{
        completion(YES);
    }
}

-(NINavigationController *)getNavigationController
{
    
    NINavigationController *nav = (NINavigationController *)self.navigationController;
    NSLog(@"viewControllers = %@",nav.viewControllers);
    if (nav == nil) {
        
        MainViewController *mainViewController = (MainViewController *)[self findViewControllerWithClass:[MainViewController class]];
        nav = (NINavigationController *)mainViewController.navigationController;
    }
    return nav;
}





#pragma mark -------- 旋转相关 --------

-(void)setOrientationLandscapeRight
{
    UINavigationController *nav = self.navigationController;
    if ([nav isKindOfClass:[NINavigationController class]]) {
        
        // 强制横屏
        [self forceOrientationLandscape];
        
        NINavigationController * navigation = (NINavigationController *)nav;
        navigation.interfaceOrientation = UIInterfaceOrientationLandscapeRight;
        navigation.interfaceOrientationMask = UIInterfaceOrientationMaskLandscapeRight;
        
        //强制翻转屏幕，Home键在右边。
        //        [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight) forKey:@"orientation"];
        
        [self orientationToPortrait:UIInterfaceOrientationLandscapeRight];
        //刷新
        [UIViewController attemptRotationToDeviceOrientation];
    }
}


//强制旋转屏幕
- (void)orientationToPortrait:(UIInterfaceOrientation)orientation {
    SEL selector = NSSelectorFromString(@"setOrientation:");
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
    [invocation setSelector:selector];
    [invocation setTarget:[UIDevice currentDevice]];
    int val = orientation;
    [invocation setArgument:&val atIndex:2];//前两个参数已被target和selector占用
    [invocation invoke];
    
}

-(void)setOrientationLandscapePortrait
{
    UINavigationController *nav = self.navigationController;
    if ([nav isKindOfClass:[NINavigationController class]]) {
        //强制旋转竖屏
        [self forceOrientationPortrait];
        NINavigationController *navi = (NINavigationController *)self.navigationController;
        navi.interfaceOrientation = UIInterfaceOrientationPortrait;
        navi.interfaceOrientationMask = UIInterfaceOrientationMaskPortrait;
        
        //设置屏幕的转向为竖屏
        //        [[UIDevice currentDevice] setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
        [self orientationToPortrait:UIInterfaceOrientationPortrait];
        //刷新
        [UIViewController attemptRotationToDeviceOrientation];
    }
}
//强制横屏
- (void)forceOrientationLandscape{
    
    AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    appdelegate.isForceLandscape=YES;
    appdelegate.isForcePortrait=NO;
    [appdelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
}

//强制竖屏
- (void)forceOrientationPortrait{
    
    AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    appdelegate.isForcePortrait=YES;
    appdelegate.isForceLandscape=NO;
    [appdelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
}

- (void)dealloc{
    
    [self viewDidBack];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

@end
